package com.example.demo.check.impl;

import com.example.demo.check.MyPermissionChecker;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;
@Component
public class MyPermissionCheckerImpl implements MyPermissionChecker {
    /**
     * 每次请求时都传递一个参数,参数名字perm,参数的值是权限标记.比如login:login ; user:manager等
     * 检查权限时,设定规则如下:
     * 1.如果访问路径是/login,/userLogin,/loginFail 不检查权限,直接放行
     * 2.其他的访问路径地址,则获取请求参数,参数名perm,值是此请求地址必须拥有的权限描述.
     * @param request
     * @param authentication Security框架管理的认证用户主体对象
     *                       在内存中具体类型是UsernamePasswordAuthenticationToken
     * @return
     */
    @Override
    public boolean check(HttpServletRequest request, Authentication authentication) {
        //1.获取本次请求的路径地址
        String path = request.getServletPath();
        //判断请求地址是否直接放行
        if ("/login".equals(path) || "/userLogin".equals(path) || "loginFail".equals(path)){
            return true;
        }
        //获取请求参数
        String perm = request.getParameter("perm");
        //获取权限前,判断是否已登录
        if (authentication != null && authentication.isAuthenticated()){
            //获取当前已认证登录的用户的权限
            Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
            //判断权限集合中是否存在当前请求需要的权限
            if (authorities.contains(new SimpleGrantedAuthority(perm))){
                //有权限
                return true;
            }
        }else {
            return false;
        }
        //没有权限
        return false;
    }
}
